package app.sceledroid.network;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import app.sceledroid.entity.Course;
import app.sceledroid.entity.Forum;
import app.sceledroid.entity.User;
import app.sceledroid.entity.forum.Discussion;
import app.sceledroid.services.SceleService;

public class DiscussionGrabber extends AsyncTask<Forum, Void, ArrayList<Discussion>> {

	private Context context;
	private DefaultHttpClient client;
	private ProgressDialog dialog;
	private SceleService sceleService;

	public DiscussionGrabber(Context context, DefaultHttpClient client,
			SceleService sceleService) {
		super();
		this.context = context;
		this.client = client;
		this.sceleService = sceleService;
	}

	@Override
	protected void onPostExecute(ArrayList<Discussion> result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
	}

	@Override
	protected void onProgressUpdate(Void... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
	}

	@Override
	protected ArrayList<Discussion> doInBackground(Forum... forums) {
		// TODO Auto-generated method stub
		
		ArrayList<Discussion> discussions = new ArrayList<Discussion>();
		Forum c = forums[0];
		
		c.setDiscussions(discussions);
		
		try {
		
			HttpGet request = new HttpGet(c.getUrl());
			HttpResponse response = client.execute(request);
			InputStream stream = response.getEntity().getContent();
			
			Document doc = Jsoup.parse(stream, "UTF-8", c.getUrl());
			
			Elements discussionElements = doc.select("tr.discussion");
			for(Element elem : discussionElements)
			{
				Element el = elem.select("td.topic a").first();
				String topic = el.text() ;
				String url = el.attr("href");
				el = elem.select("td.author a").first();
				User creator = new User(el.text(),"","") ;
				Elements els = elem.select("td.lastpost a");
				String lastResponse = els.text();
				Discussion d = new Discussion(creator, url, topic, lastResponse); 
				
				discussions.add(d);
			}
			Log.v("Document", doc.text());
			
			
			return discussions;
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

}
